<?php
/**
 * 提现
 */
namespace App;
defined('IN_IA') or exit('Access Denied');

use Model\CashMod;
use Model\MemberMod;
use Model\WqMemberMod;
use Pub\tool\Setting;
use Pub\tool\Tool;
use Pub\wx\WxPay;

class Cash extends Action
{
    private $Cash = null;
    private $Member = null;

    public function __construct()
    {
        parent::__construct();
        $this->Cash = new CashMod();
        $this->getUid();
    }

    /**
     * 提现
     * @param string money 提现金额
     * @param string uid 用户id
     */
    public function cash()
    {
        $_lowest_cash = Setting::get(Setting::LOWEST_CASH);
        //最低提现金额
        if($this->_gpc['money'] < $_lowest_cash){
            $this->_result = array('status'=>'error','err_status'=>1,'err_msg'=>'提现金额不能小于'.$_lowest_cash.'元');
            $this->result($this->_result);
        }
        //用户余额验证,判断用户使用的微擎官方余额还是模块独立余额
        $_use_balance = Setting::get(Setting::USE_BALANCE);
        $this->Member = $_use_balance ==1 ? new MemberMod() : new WqMemberMod();
        if($_use_balance == 1){
            $_member = $this->Member->findOne(array('uid'=>$this->_uid,'uniacid'=>$this->_uniacid),array('balance','id'));
            $_balance = $_member['balance'];
        }else{
            $_member = $this->Member->findOne(array("uid"=>$this->_uid),array("credit2"));
            $_balance = $_member["credit2"];
        }
        if($this->_gpc['money'] > $_balance){
            $this->_result = array('status'=>'error','err_status'=>2,'err_msg'=>'余额不足~');
            $this->result($this->_result);
        }
        //减去用户提现余额
        if($_use_balance == 1){
            $this->Member->math(array('balance -'=>$this->_gpc['money']),array('id'=>$_member['id']));
        }else{
            mc_credit_update($this->_uid,"credit2","-".$this->_gpc['money']);
        }
        //创建提现数据
        $_cash_order_id = Tool::createOrder();
        $_create_cash = $this->Cash->insert(array(
            'uniacid'=>$this->_uniacid,
            'order_id'=>$_cash_order_id,
            'uid'=>$this->_uid,
            'money'=>$this->_gpc['money'],
            'time'=>TIMESTAMP
        ));
        $_cash_id = pdo_insertid();
        //是否自动提现至微信钱包
        $_auto_cash = Setting::get(Setting::AUTO_CASH);
        if($_auto_cash == 0 || $this->_gpc['money'] >= $_auto_cash){
            $this->_result = array('status'=>'success','auto'=>false);
            $this->result($this->_result);
        }
        //是自动到账的
        $WxPay = new WxPay($_cash_order_id);
        $_fans = $this->uidToFans($this->_uid);
        $_openid = KUYUAN_DEBUG ? 'oxYQT1DAyMPEFXMzjjJ-Rz1OQa-c' : $_fans['openid'];
        $_remark = Setting::get(Setting::CASH_REMARK);
        $_wx_payer = $WxPay->payer($_openid,$this->_gpc['money'],$_remark ? $_remark : "提现到账");
        if($_wx_payer['status'] == 'success'){
            $this->Cash->update(array('status'=>1),array('id'=>$_cash_id));
            $this->_result = array('status'=>'success','auto'=>true);
            $this->result($this->_result);
        }else{
            $this->Cash->update(array('status'=>9),array('id'=>$_cash_id));
            if($_use_balance === 1){
                $this->Member->math(array('balance +'=>$this->_gpc['money']),array('id'=>$_member['id']));
            }else{
                mc_credit_update($this->_uid,"credit2",$this->_gpc['money']);
            }
            $this->_result = array('status'=>'error','err_status'=>3,'err_msg'=>$_wx_payer['err_msg']);
            $this->result($this->_result);
        }
    }

    /**
     * 获取用户提现列表
     * @param string uid 用户id
     */
    public function getUserList()
    {
        $_list = $this->Cash->findAll(
            array('uid'=>$this->_uid,'uniacid'=>$this->_uniacid,'status !='=>9),
            array('order'=>array('status','asc','id','desc'),'limit'=>$this->_gpc['limit']),
            array('id','money','status','time')
        );
        if(count($_list) > 0){
            foreach($_list as $_k=>$_v){
                $_list[$_k]['time'] = date('Y-m-d H:i:s',$_v['time']);
            }
            $this->_result = array('status'=>'success','data'=>$_list);
        }
        $this->result($this->_result);
    }

    //-----------web端--------------------------

    /**
     * 获取提现列表总数
     * @param integer status 状态
     */
    public function getTotal()
    {
        $_where = array("uniacid"=>$this->_uniacid,"status"=>$this->_gpc["status"]);
        $this->_result = array("status"=>"success","data"=>$this->Cash->total($_where));
        $this->result($this->_result);
    }

    /**
     * 获取提现列表
     * @param integer status 状态
     * @param array limit 请求下标
     */
    public function getList()
    {
        $_where = array("uniacid"=>$this->_uniacid,"status"=>$this->_gpc["status"]);
        $_list = $this->Cash->findAll(
            $_where,
            array("order"=>array("id","desc"),"limit"=>$this->_gpc["limit"]),
            array("id","uid","money","status","time")
        );
        if(count($_list) > 0){
            foreach($_list as $_k=>$_v){
                $_member = $this->uidToInfo($_v["uid"]);
                $_list[$_k]["nickname"] = $_member["nickname"];
                $_list[$_k]["time"] = date("Y-m-d H:i:s",$_v["time"]);
            }
            unset($_member);
            $this->_result = array("status"=>"success","data"=>$_list);
        }
        $this->result($this->_result);
    }

    /**
     * 修改提现状态
     * @param integer cash_id 提现id
     * @param integer status 目标状态
     */
    public function changeStatus()
    {
        $_status = $this->_gpc["status"];
        $_cash = array();  //提现数据
        if($_status == 1 || $_status == 2){
            $_cash = $this->Cash->findOne(array("id"=>$this->_gpc["cash_id"]),array("order_id","money","uid"));
            $this->Member = new MemberMod();
            if($_status == 1){
                $_cash_result = $this->wxCash($_cash["order_id"],$_cash["uid"],$_cash["money"]);
                if($_cash_result["status"] != "success"){
                    $this->_result = array("status"=>"error","err_msg"=>$_cash_result["err_msg"]);
                    $this->result($this->_result);
                }
            }else if($_status == 2){
                //将余额退回给用户
                $_use_balance = Setting::get(Setting::USE_BALANCE);
                if($_use_balance == 1){
                    $this->Member->math(array("balance +"=>$_cash["money"]),array("uniacid"=>$this->_uniacid,"uid"=>$_cash["uid"]));
                }else{
                    mc_credit_update($_cash["uid"],"credit2",$_cash["money"]);
                }
            }
        }
        if($this->Cash->update(array("status"=>$_status),array("id"=>$this->_gpc["cash_id"]))){
            $this->_result = array("status"=>"success");
        }
        $this->result($this->_result);
    }

    /**
     * 批量提现
     * @param array data 提现数据
     */
    public function cashAll()
    {
        $_success = 0;
        $_error = 0;
        foreach($this->_gpc["data"] as $_v){
            $_cash = $this->Cash->findOne(array("id"=>$_v),array("order_id","uid","money"));
            $_cash_result = $this->wxCash($_cash["order_id"],$_cash["uid"],$_cash["money"]);
            if($_cash_result["status"] == "success"){
                $_success++;
                $this->Cash->update(array("status"=>1),array("id"=>$_v));
            }else{
                $_error++;
            }
        }
        unset($_cash,$_cash_result);
        $this->_result = array('status'=>'success','data'=>'成功提现'.$_success.'条，失败提现'.$_error.'条。');
        $this->result($this->_result);
    }

    /**
     * 微信提现
     * @param integer $_order_id  订单id
     * @param integer $_uid  用户id
     * @param double $_money 提现金额
     * @return array 提现处理信息
     */
    public function wxCash($_order_id,$_uid,$_money)
    {
        $WxPay = new WxPay($_order_id);
        $_fans = $this->uidToFans($_uid);
        $_openid = KUYUAN_DEBUG ? 'oxYQT1DAyMPEFXMzjjJ-Rz1OQa-c' : $_fans['openid'];
        $_remark = Setting::get(Setting::CASH_REMARK);
        return $WxPay->payer($_openid,$_money,$_remark ? $_remark : "提现成功");
    }
}